﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK_WMS.Model.Helper
{
    public class HttpHelper
    {
        private static readonly HttpClient _httpClient = new HttpClient();

        private static readonly string baseUrl = "http://example.com"; // 请替换为实际的baseUrl

        public static async Task<string> SendGetRequest(string url, Dictionary<string, string> queryParams = null)
        {
            try
            {
                if (queryParams != null)
                {
                    var queryString = new FormUrlEncodedContent(queryParams);
                    url += $"?{queryString.ReadAsStringAsync().Result}";
                }

                HttpResponseMessage response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                // 处理异常，例如记录日志或抛出自定义异常
                Console.WriteLine($"An error occurred: {ex.Message}");
                throw;
            }
        }

        public static async Task<string> SendPostRequest(string url, string requestBody, Dictionary<string, string> queryParams = null)
        {
            try
            {
                if (queryParams != null)
                {
                    var queryString = new FormUrlEncodedContent(queryParams);
                    url += $"?{queryString.ReadAsStringAsync().Result}";
                }

                HttpContent content = new StringContent(requestBody);
                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                response.EnsureSuccessStatusCode();

                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine($"An error occurred: {ex.Message}");
                throw;
            }
        }

        public static string GetFullUrl(string path)
        {
            return $"{baseUrl}/{path}";
        }
    }
}
